package com.kws.tool.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kws.common.core.domain.R;
import com.kws.common.redis.service.RedisService;
import com.kws.tool.service.MsmService;
import com.kws.tool.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
@Api(value = "短信", tags = "短信")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisService redisService;

    //发送短信的方法
    @GetMapping("/sendCode/{phone}")
    @ApiOperation("验证码")
    public R sendCode(@PathVariable String phone) {
        if (StringUtils.isEmpty(phone)){
            return R.fail("手机号不能为空！");
        }
        //1 从redis获取验证码，如果获取到直接返回
        String code = redisService.getCacheObject(phone);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //2 如果redis获取 不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        param.put("codeType","authCode");
        param.put("phone",phone);
        //调用service发送短信的方法
        boolean isSend = msmService.sendCode(param);
        if(isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisService.setCacheObject(phone,code, 5L,TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.fail("短信发送失败");
        }
    }

    //发送短信的方法
    @PostMapping("sendMsm")
    @ApiOperation("其他短信发送")
    public R sendMsm(@RequestBody Map<String,Object> param) {
        //调用service发送短信的方法
        boolean isSend = msmService.sendCode(param);
        if(isSend) {
            return R.ok();
        } else {
            return R.fail("短信发送失败");
        }
    }
}
